<template>
  <div>
    <el-dialog
      :title="dataForm.hotSearchId ? $t('table.edit') : $t('table.create')"
      :visible.sync="visible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="店铺名称：" prop="shopName">
          <el-input
            placeholder="请输入店铺名称："
            v-model="dataForm.shopName"
            style="width: 60%"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="关联吧台：" prop="barCounterNumber">
          <el-select
            style="width: 60%"
            v-model="dataForm.barCounterNumber"
            size="mini"
            placeholder="请选择关联吧台"
            clearable
            @change="barCounterChange"
          >
            <el-option 
              v-for="(item, index) in barCounterList"
              :key="index"
              :label="item.number"
              :value="item.barCounterId"
              />
          </el-select>
        </el-form-item> -->
        <el-form-item label="店铺位置：" prop="barCounterRegion">
          <el-input
            placeholder="请输入吧台位置："
            v-model="dataForm.barCounterRegion"
            style="width: 60%"
            disabled
          ></el-input>
          <i class="el-icon-location" style="font-size: 20px" @click="mapView" ></i>
        </el-form-item>
        <el-form-item label="分账方式：">
          <el-radio-group v-model="dataForm.allocationMode" @change="radioChange">
            <el-radio-button label="1">商品佣金</el-radio-button>
            <el-radio-button label="2">订单分账</el-radio-button>
            <el-radio-button label="3">无</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分账收益：">
          <el-input style="width: 60%" v-if="dataForm.allocationMode == 1" placeholder="获得金额..." v-model="dataForm.yuan">
            <i class="el-input__icon" slot="suffix" style="padding-right: 10px">元</i>
            <template slot="prepend">每卖出商品</template>
          </el-input>
          <el-input style="width: 60%" v-if="dataForm.allocationMode == 2" placeholder="获得该笔订单%的分销..." v-model="dataForm.ratio">
            <i class="el-input__icon" slot="suffix" style="padding-right: 10px">%</i>
            <template slot="prepend">每笔订单</template>
          </el-input>
          <div v-if="dataForm.allocationMode == 3">无</div>
        </el-form-item>
        <el-form-item label="设备绑定：" prop="address">
          <el-button type="primary" plain style="margin-bottom: 10px">新增设备</el-button>
          <el-table border :data="tableData" style="width: 100%">
            <el-table-column prop="date" label="设备名称" ></el-table-column>
            <el-table-column prop="name" label="网关地址" ></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('dataForm')">确定</el-button>
        <el-button @click="resetForm('dataForm')">取消</el-button>
      </div>
    </el-dialog>
     <!-- 弹窗, 新增 / 修改 -->
    <el-dialog title="选择地区" :visible.sync="visibleMap">
      <el-select
        v-model="dataForm.barCounterRegion"
        style="width: 400px"
        clearable
        :filter-method="changeMap"
        filterable
        placeholder="请选择"
      >
        <el-option
          v-for="item in dataSource"
          :key="item.id"
          :value="item.formatted_address + ''"
          :label="item.formatted_address"
        >
        </el-option>
      </el-select>
      <div style="height: 300px; margin-top: 10px">
        <el-amap
          vid="amap"
          class="amap-demo"
          ref="amap"
          :zoom="zoom"
          :events="events"
        >
          <!-- 点击显示标记 -->
          <el-amap-marker
            v-for="(marker, index) in markers"
            :key="marker.index"
            :position="marker.position"
            :icon="marker.icon"
            :title="marker.title"
            :events="marker.events"
            :visible="marker.visible"
            :draggable="marker.draggable"
            :vid="index"
          ></el-amap-marker>
        </el-amap>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visibleMap = false"> 取消 </el-button>
        <el-button type="primary" @click="visibleMap = false"> 确定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import city from '../../../../mock/city.json'
import * as apis from "@/api/selfoperated/index";
import * as api from "@/api/shop/index";
import Axios from "axios";
export default {
  data() {
    const self = this
    return {
      visible: false,
      dataForm: {
        shopName: null,
        // barCounterNumber: null,
        barCounterRegion: null,
        allocationMode: 1,
        yuan: null,
        ratio: null
      },
      rules: {
        shopName: [{ required: true, message: "店铺名称不能为空", trigger: "blur" }],
        // barCounterNumber: [{ required: true, message: "请选择吧台", trigger: "change" }],
        barCounterRegion: [{ required: true, message: "请选择位置", trigger: "change" }],
      },
      visibleMap: false,
      barCounterList: [],
      dataSource: [],
      // 高德地图
      map: {
        address: "",
        lng: "",
        lat: "",
      },
      zoom: 18, // 地图缩放
      center: [], // 初始中心
      markers: [],
      lng: 0, //经纬度
      lat: 0,
      loaded: false,
      address: "", //获取的位置
      // 点击地图获取当前位置并显示标记
      events: {
        click(e) {
          self.chaadd(e.lnglat);
        },
      },
      areaList: [],
      tableData: [],
    };
  },

  mounted() {
    this.getArea()
    this.getBarCounter()
  },

  methods: {
    init(barCounterShopId) {
      this.dataForm.barCounterShopId = barCounterShopId || 0;
      this.visible = true;
      if (this.dataForm.barCounterShopId) {
        this.$nextTick(() => {
          if (barCounterShopId) {
            api.get(barCounterShopId).then(data => {
              this.dataForm = data
            })
          }
        });
      } else {
        this.$refs['dataForm'].resetFields()
        this.dataForm = {
          allocationMode: 1,
          yuan: null,
          ratio: null
        }
      }
    },
    getArea() {
      city.forEach(item => {
        item.label = item.province
        item.value = item.province
        if (item.citys && item.citys.length > 0) {
          item.children = item.citys
          item.children.forEach(i => {
            i.label = i.city
            i.value = i.city
            if (i.areas && i.areas.length > 0) {
              i.children = i.areas
              i.children.forEach(v => {
                v.label = v.area
                v.value = v.area
              })
            }
          })
        }
      })
      this.areaList = city
    },
    getBarCounter() {
      apis.getPage({ pageNum: 1, pageSize: 99 }).then((pageVO) => {
        this.barCounterList = pageVO.list
        this.pageVO = pageVO;
      });
    },
    // 点击地图坐标
    chaadd(e) {
      let self = this
      let { lng, lat } = e
      self.lng = lng
      self.lat = lat
      self.map.lng = self.lng
      self.map.lat = self.lat
      self.center = [self.lng, self.lat]
      self.loaded = true
      var geocoder = new AMap.Geocoder({
        radius: 1000, //范围，默认：500
      })
      self.markers = [
        {
          position: self.center,
        },
      ]
      function regeoCode() {
        var lnglat = [lng, lat]
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            self.dataForm.barCounterRegion = result.regeocode.formattedAddress
            self.map.address = self.address
            self.map.position = self.center
            self.map.offset = [5, -15]
            self.map.content = `<div>${self.map.address}</div>`
            self.map.visible = true
          } else {
            self.address = undefined
            self.lng = undefined
            self.lat = undefined
            self.$message({
              type: 'error',
              message: '根据经纬度查询地址失败',
            })
          }
        })
      }
      regeoCode()
      console.log('mapDing', self.map)
    },
    mapView() {
      this.visibleMap = true;
    },
    barCounterChange(e) {
      if (e) {
        this.dataForm.number = e
      } else {
        delete this.dataForm.number
      }
    },
    changeMap(e, cb) {
      // 输入框内容变化时的处理逻辑
      this.map = [];
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        if (e) {
          this.searchMap(e);
        }
      }, 3000);
    },
    searchMap(value) {
      Axios.get(`http://restapi.amap.com/v3/geocode/geo`, {
        params: {
          key: process.env.VUE_APP_AMAPKEY_WEB_END,
          address: value,
        },
      }).then((res) => {
        this.dataSource = res.data.geocodes;
        if (
          res &&
          res.data &&
          res.data.geocodes &&
          res.data.geocodes.length > 0
        ) {
          let location = res.data.geocodes[0].location.split(",");
          this.lng = location[0];
          this.lat = location[1];
          this.dataForm.barCounterRegion = res.data.geocodes[0].formatted_address;
          this.map.address = this.address;
          this.map.position = this.center;
          this.map.offset = [5, -15];
          this.map.content = `<div>${this.map.address}</div>`;
          this.map.visible = true;
          this.markers.push({
            position: location,
            zoom: 18,
            center: [this.lng, this.lat],
          });
          this.$refs.amap.$amap.setZoomAndCenter(12, [this.lng, this.lat]);
        }
      });
    },
    radioChange(e) {
      if (e == 1) {
        this.dataForm.ratio = null
      } else if (e == 2) {
        this.dataForm.yuan = null
      } else {
        this.dataForm.ratio = null
        this.dataForm.yuan = null
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.dataForm)
          const request = this.dataForm.barCounterShopId ? api.update(this.dataForm) : api.addsave(this.dataForm)
          request.then(data => {
          this.$message({
            message: this.$t('table.actionSuccess'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
              this.dataForm = {
                allocationMode: 1,
                yuan: null,
                ratio: null
              }
              this.$refs['dataForm'].resetFields()
            }
          })
        })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dataForm = {
        allocationMode: 1,
        yuan: null,
        ratio: null
      }
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
</style> 